import sys
import os
from PyQt6.QtWidgets import QApplication, QSplashScreen, QMessageBox
from PyQt6.QtGui import QIcon, QPixmap
from PyQt6.QtCore import Qt, QTimer

# 确保能够导入自定义模块
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from ui.main_window import MainWindow
from core.browser import BrowserWorker


class Application:
    """应用程序主类，连接UI和浏览器自动化功能"""
    
    def __init__(self):
        """初始化应用程序"""
        self.app = QApplication(sys.argv)
        
        # 设置应用程序属性
        self.app.setApplicationName("Claude自动化交互工具")
        self.app.setOrganizationName("Claude Automation Tools")
        self.app.setOrganizationDomain("example.com")
        
        # 设置应用程序样式
        self.app.setStyle("Fusion")
        
        # 显示启动画面
        self._show_splash_screen()
        
        # 初始化主窗口
        self.main_window = MainWindow()
        self.browser_worker = None
        
        # 连接UI和浏览器自动化
        self._connect_signals()
        
        # 隐藏启动画面并显示主窗口
        if hasattr(self, 'splash') and self.splash:
            self.splash.finish(self.main_window)
    
    def _show_splash_screen(self):
        """显示启动画面"""
        # 检查启动画面图片是否存在
        splash_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 
                                  "resources", "splash.png")
        
        if os.path.exists(splash_path):
            # 创建并显示启动画面
            splash_pixmap = QPixmap(splash_path)
            self.splash = QSplashScreen(splash_pixmap, Qt.WindowType.WindowStaysOnTopHint)
            self.splash.setMask(splash_pixmap.mask())
            self.splash.show()
            self.splash.showMessage("正在加载应用程序...", 
                                  Qt.AlignmentFlag.AlignBottom | Qt.AlignmentFlag.AlignRight, 
                                  Qt.GlobalColor.white)
            
            # 处理一些事件，以确保启动画面显示
            self.app.processEvents()
            
            # 延迟一段时间，使启动画面可见
            QTimer.singleShot(1500, lambda: None)
    
    def _connect_signals(self):
        """连接UI和浏览器工作线程的信号槽"""
        try:
            # 连接开始按钮和工作线程
            self.main_window.start_button.clicked.disconnect()
        except:
            pass
        self.main_window.start_button.clicked.connect(self._start_browser_worker)
        
        try:
            # 连接停止按钮和工作线程
            self.main_window.stop_button.clicked.disconnect()
        except:
            pass
        self.main_window.stop_button.clicked.connect(self._stop_browser_worker)
    
    def _start_browser_worker(self):
        """创建并启动浏览器工作线程"""
        # 检查提示词文件
        if not self.main_window.prompt_file_path:
            self.main_window.on_error("请先选择提示词文件")
            return
        
        try:
            # 获取浏览器类型
            browser_type = self.main_window.browser_combo.currentText().lower()
            
            # 获取自定义多轮对话提示词
            follow_up_prompts = []
            for input_widget in self.main_window.follow_up_inputs:
                follow_up_prompts.append(input_widget.text())
            
            # 创建工作线程
            self.browser_worker = BrowserWorker(
                self.main_window.prompt_file_path,
                self.main_window.iterations_spinbox.value(),
                browser_type,
                follow_up_prompts
            )
            
            # 连接信号
            self.browser_worker.progress_update.connect(self.main_window.update_progress)
            self.browser_worker.status_update.connect(self._handle_status_update)
            self.browser_worker.finished.connect(self.main_window.on_finished)
            self.browser_worker.error.connect(self.main_window.on_error)
            
            # 更新UI状态
            self.main_window.start_button.setEnabled(False)
            self.main_window.stop_button.setEnabled(True)
            self.main_window.browse_button.setEnabled(False)
            self.main_window.save_button.setEnabled(False)
            
            # 启动工作线程
            self.browser_worker.start()
            
        except Exception as e:
            QMessageBox.critical(
                self.main_window,
                "启动错误",
                f"启动自动化过程时出错: {str(e)}"
            )
            self.main_window.on_error(f"启动自动化过程时出错: {str(e)}")
    
    def _stop_browser_worker(self):
        """停止浏览器工作线程"""
        try:
            if self.browser_worker and self.browser_worker.isRunning():
                # 提示用户确认
                reply = QMessageBox.question(
                    self.main_window,
                    "确认停止",
                    "确定要停止当前的自动化流程吗？",
                    QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                    QMessageBox.StandardButton.No
                )
                
                if reply == QMessageBox.StandardButton.Yes:
                    # 停止工作线程
                    self.browser_worker.stop()
                    # 等待线程结束
                    if not self.browser_worker.wait(3000):  # 等待3秒
                        self.browser_worker.terminate()     # 强制终止
                    self.browser_worker = None
                    
                    # 更新UI状态
                    self.main_window.stop_automation()
                    
                    # 显示提示
                    self.main_window.status_bar.showMessage("自动化流程已停止", 3000)
                    
        except Exception as e:
            QMessageBox.warning(
                self.main_window,
                "停止错误",
                f"停止自动化过程时出错: {str(e)}"
            )
    
    def _handle_status_update(self, status_type, status_value):
        """处理状态更新信号"""
        if status_type == "site":
            if status_value == "已连接":
                self.main_window.site_status_label.setText(status_value)
                self.main_window.site_status_label.setStyleSheet("color: #2e7d32; padding-left: 5px;")
            else:
                self.main_window.site_status_label.setText(status_value)
                self.main_window.site_status_label.setStyleSheet("color: #f9a825; padding-left: 5px;")
        elif status_type == "model":
            if status_value == "已选择":
                self.main_window.model_status_label.setText(status_value)
                self.main_window.model_status_label.setStyleSheet("color: #2e7d32; padding-left: 5px;")
            else:
                self.main_window.model_status_label.setText(status_value)
                self.main_window.model_status_label.setStyleSheet("color: #f9a825; padding-left: 5px;")
    
    def run(self):
        """运行应用程序"""
        # 设置应用程序图标
        icon_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 
                                "resources", "app_icon.ico")
        if os.path.exists(icon_path):
            app_icon = QIcon(icon_path)
            self.app.setWindowIcon(app_icon)
            self.main_window.setWindowIcon(app_icon)
        
        # 显示主窗口
        self.main_window.show()
        
        # 运行应用程序事件循环
        return self.app.exec()


def main():
    """应用程序入口点函数"""
    # 捕获全局异常
    try:
        app = Application()
        return app.run()
    except Exception as e:
        error_msg = f"应用程序运行时遇到致命错误: {str(e)}"
        print(error_msg)
        
        # 尝试显示错误对话框
        try:
            QMessageBox.critical(None, "致命错误", error_msg)
        except:
            pass
        
        return 1


if __name__ == "__main__":
    sys.exit(main()) 